import { watch, ref, computed, nextTick, Ref, ComputedRef, onUnmounted } from 'vue'
import _ from 'lodash'

interface Params {
    cb?: (data: any) => void
}

export default (p?: Params): [Ref<any>, (data: any) => void] => {
    const receptionDataEKey = `REMOTE_COMPONENT_BUSINESS_PROPS_CHANGE_${window.__WUJIE.id}`
    const dispatchDataEKey = `REMOTE_COMPONENT_VIEW_DATA_UPDATE_${window.__WUJIE.id}`

    // 初始化获取
    const state = ref<any>(window.$wujie?.props.remoteData)

    function _getData(remoteData: any) {
        state.value = _.cloneDeep(remoteData)
        p?.cb?.(remoteData)
    }

    window.$wujie?.bus.$on(receptionDataEKey, _getData)

    function setState(localData: any) {
        window.$wujie?.bus.$emit(dispatchDataEKey, localData)
    }

    onUnmounted(() => {
        window.$wujie?.bus.$off(receptionDataEKey, _getData)
    })

    return [state, setState]
}
